<?php
namespace app\admin\controller;

use app\admin\common\controller\Base;
use app\admin\common\model\Major as majorModel;
use app\admin\common\model\Department as departmentModel;
use think\facade\Request;

class Major extends Base
{
    public function index()
    {
        $major_id=Request::param('major_id');
        if($major_id){
            $majorList=majorModel::where('department_id',$major_id)->paginate(10);
        }else{
            $majorList=majorModel::paginate(10);
        }
        foreach($majorList as $major){
            $temp=$major['department_id'];
            $departmentMajor=departmentModel::where('id',$temp)->find();
            $major['department_id']=$departmentMajor['name'];
        }
        $departmentList=departmentModel::where('name','<>','校总办')->where('name','<>','学生处')->order('weight desc')->select();        
        $this->view->assign('majorList',$majorList);
        $this->view->assign('departmentList',$departmentList);
        $this->view->assign('title','专业');
        return $this->view->fetch();
    }
    
    //执行删除
    public function doDelete()
    {
        //1，获取当前要删除的主键id
        $id=Request::param('id');
        //2，执行删除
        if(majorModel::where('id',$id)->delete())
        {
            return $this->success('删除成功','admin/Major/index');
        }
        else
        {
            return $this->error('删除失败','admin/Major/index');
        }
    }
    
    //用户编辑
    public function majorEdit()
    {
        //1，获取当前更新的用户的主键
        $majorId=Request::param('id');
        //2，根据主键进行查询
        $majorInfo=majorModel::where('id',$majorId)->find();
        //3，设置编辑界面的模板变量
        $this->view->assign('title','更改用户信息');
        $this->view->assign('majorInfo',$majorInfo);
        $this->view->assign('title','专业');
        //4，渲染出编辑页面
        return $this->view->fetch('majorEdit');
    }
    
    //执行用户编辑的信息
    public function doEdit()
    {
        //1，获取到用户提交的信息
        $data=Request::post();
        //2，取出主键    
        $id=$data['id'];
        //4，删除主键id，只有删除主键之后才能将新的数据加入到数据表中
        unset($data['id']);
        //5，执行更新操作
        if(majorModel::where('id',$id)->data($data)->update())
        {
            return $this->success('更新成功','admin/Major/index');
        }  
    }
    
    //添加数据验证
    public function insertMajor()
    {
        if ( Request::isAjax() ) {
            //使用模型来创建数据
            //验证数据
            $data = Request::post(); //要插入的数据
            if ( $user = majorModel::create( $data ) ) {
                    return [ 'status' => 1, 'message' => '插入数据成功' ];
                } else {
                    return [ 'status' => 0, 'message' => '插入数据失败' ];
                }             
        } else {
            $this->error( "请求类型错误", 'admin/Major/index' );
        }
    }
   
    //验证是否有重复名字
    public function namevalidte()
    {
        if(Request::isAjax()){
            $nameInput=input('nameInput');
            $res=majorModel::where('major',$nameInput)->find();
            if($res){
                return ['status'=>1,'message'=>'名称已存在！'];
            }else{
                return ['status'=>0,'message'=>''];
            }      
        }else{
            $this->error("请求类型出错",'admin/Major/index');
        }
    }
    
    //	批量删除
    public function delete()
    {
        //	获取前台删除的全部id  (/a强制转换为数组类型)
        // 因为修改是根据主键id修改的  所以要用修饰符转换一下
        $data=input('ids/a');
        //	调用model里面的destroy方法 传参是删除的ID 
        $info = majorModel::destroy($data);
        //	判断是否删除成功
        if($info){
            $this->success('批量删除成功');
        }else{
            $this->error('请在选择你要删除的内容');
        }
    }
    
//    文件导出
   public function output()
   {
       $res = majorModel::field(['major','department_id','major_number','major_code','learning','level','subject'])->select();
       foreach($res as $major){
            $temp=$major['department_id'];
            $departmentMajor=departmentModel::where('id',$temp)->find();
            $major['department_id']=$departmentMajor['name'];
        }
//       对象转换为数组
       $data=json_decode(json_encode($res), true);
       
    $title = ['专业名称', '院系','专业编号','国际专业代码','学制','培养层次','所属学科'];
    // Create new Spreadsheet object
    $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
 
    // 方法二，使用 setCellValue
    //表头
    //设置单元格内容
    $titCol = 'A';
    foreach ($title as $key => $value) {
        // 单元格内容写入
        $sheet->setCellValue($titCol . '1', $value);
        $titCol++;
    }
    $row = 2; // 从第二行开始
    foreach ($data as $item) {
        $dataCol = 'A';
        foreach ($item as $value) {
            // 单元格内容写入
            $sheet->setCellValue($dataCol . $row, $value);
            $dataCol++;
        }
        $row++;
    }
 
    // Redirect output to a client’s web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="专业管理.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
 
    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0
 
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output'); 
       exit;
   }
    
//    模板下载
    public function templateDown()
    {
        $title = ['专业名称', '院系','专业编号','国际专业代码','学制','培养层次','所属学科'];
        // Create new Spreadsheet object
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        // 方法二，使用 setCellValue
        //表头
        //设置单元格内容
        $titCol = 'A';
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }
        
        // Redirect output to a client’s web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="专业管理模板.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
 
    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0
 
    $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->save('php://output'); 
       exit;
        }
        
    //模糊搜寻
    public function searchform()
    {
        $search=Request::post();
        $searchname=$search['searchname'];
        $form=$search['form'];
        $majorInfo = majorModel::where($form,'like','%' . $searchname . '%')->paginate(10);
        $this->assign('majorInfo',$majorInfo);
        if($form =='major'){
            $form = '专业名称';
        }
        if($form =='campus'){
            $form = '院系';
        }
        if($form =='major_number'){
            $form = '专业编号';
        }
        if($form =='major_code'){
            $form = '国际专业代码';
        }
        $departmentList=departmentModel::select();
        $this->view->assign('departmentList',$departmentList);
        $this->assign('form',$form);
        $this->assign('searchname',$searchname);
        $this->view->assign('title','专业');
        return $this->fetch('searchform');
        
    }
        
}